package com.dubbo.framework.http;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.ErrorPage;

import java.io.File;

/**
 * @author yangjian
 **/
public class HttpServer
{
    public void start(String hostname, Integer port)
    {
        Tomcat tomcat = new Tomcat();
        // 配置 tomcat
        tomcat.setHostname(hostname);
        tomcat.setPort(port);
        // 设置 webapp 路径
        Context context = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());

        // 设置错误页面
        ErrorPage errorPage = new ErrorPage();
        errorPage.setErrorCode(404);
        errorPage.setLocation("/error.html");
        context.addErrorPage(errorPage);

        Tomcat.addServlet(context, "dispatcherServlet", new DispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcherServlet");

        // 启动服务
        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }
}
